#include "c_mem.h"

/**
 * @brief 计算字符串长度，0是结束符
 * 
 * @param cptr 
 * @return int 
 */
int c_strlen(char *cptr)
{
	int len = 0;

	while (*cptr++) len++;
	return len;
}

/**
 * @brief 复制字符串
 * 
 * @param pptr 
 * @param sptr 
 */
void c_strcpy(char *pptr, const char *sptr)
{
	do {
		*pptr++ = *sptr;
	}
	while (*sptr++);
}

/**
 * @brief 字符串比较
 * 
 * @param ptr1 
 * @param ptr2 
 * @return int 
 */
int c_strcmp(const char * ptr1, const char * ptr2)
{
	while ((*ptr1!=0) && (*ptr2!=0) && (*ptr1==*ptr2))
	{
		ptr1++;
		ptr2++;
	}
	return *ptr1 - *ptr2;
}

/**
 * @brief 字符串连接
 * 
 * @param s 
 * @param t 
 */
void c_strcat(char *s, char *t)
{
	while (*s++);
	do {
		*s++ = *t++;
	} while(*t);
}


/**
 * @brief 内存拷贝
 * 
 * @param dst 
 * @param src 
 * @param len 
 */
void c_memcpy(void *dst, const void *src, unsigned int len)
{
    char *pdst = (char *)dst;
    const char *psrc = (char *)src;
    
    while (len--) {
        *pdst++ = *psrc++;    
    }
}

/**
 * @brief 内存清理
 * 
 * @param dst 
 * @param len 
 */
void c_bzero(void *dst, unsigned int len)
{
    char *pdst = (char *)dst;
    while (len--) {
        *pdst++ = 0;  
    }
}

/**
 * @brief 内存设置
 * 
 * @param dst 
 * @param c 
 * @param len 
 */
void c_memset(void *dst, int c, unsigned int len)
{
    
    char *pdst = (char *)dst;
    while (len--) {
        *pdst++ = (char)c;
    }       
}

/**
 * @brief  安全内存拷贝
 * 
 * @param dest - where to copy to
 * @param src - where to copy from
 * @param count - the size of the area.
 * @return void* 
 * 
 * Unlike memcpy(), memmove() copes with overlapping areas.
 */
void* c_memmove (void * dest, const void *src, size_t count)
{
	char *tmp, *s;

	if (dest <= src) {
		tmp = (char *) dest;
		s = (char *) src;
		while (count--)
			*tmp++ = *s++;
	} else {
		tmp = (char *) dest + count;
		s = (char *) src + count;
		while (count--)
			*--tmp = *--s;
	}

	return dest;
}

/**
 * @brief 字符转十六进制
 * 	
 * @param c 
 * @return int 
 * 
 * 例如：'F'将转为0x0F。
 */
int ctohex(char c)
{
    if (c >= '0' && c <='9')
        return (c - '0');
    else if (c >= 'a' && c <='f')
        return (10 + c - 'a');
    else if (c >= 'A' && c <='F')
        return (10 + c - 'A');
    else
        return -1;
}


